package com.xes.attend.rd60n.jiecard.cn;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;

public class TCPClientConn implements NetConn {
	private String dev_ip;
	private Socket tcp_client;
	private long last_time;

	private int ConnectTo() {
		try {
			do {
				if (null != tcp_client) {
					if (last_time > (new Date()).getTime() - 8) {
						Close();
					}
				}
				if (null == tcp_client) {
					tcp_client = new Socket();
					InetAddress addr = InetAddress.getByName(dev_ip);
					tcp_client.connect(new InetSocketAddress(addr, 8013), 3000);
					tcp_client.setSoTimeout(3000);
					tcp_client.setTcpNoDelay(true);
				}

			} while (false);
		} catch (Exception e) {
			Close();
			e.printStackTrace();
		}
		if (tcp_client == null)
			return 1;
		else
			return 0;

	}

	@Override
	public int SendData(byte[] Data) {
		int result = 1;
		try {
			do {
				if (0 != ConnectTo())
					break;
				OutputStream out = tcp_client.getOutputStream();
				out.write(Data);
				result = 0;
			} while (false);
		} catch (Exception e) {
			Close();
			e.printStackTrace();
		}
		return result;

	}

	@Override
	public byte[] RecvData(int len) {
		byte[] recv_data = new byte[len];
		int result = 1;
		try {
			do {
				if (0 != ConnectTo())
					break;
				InputStream in = tcp_client.getInputStream();
				int l = 0;
				int tmp;
				while (len > 0) {
					tmp = in.read(recv_data, l, len);
					if(tmp < 0) break;
					l += tmp;
					len -= tmp;
				}
				if(len !=0 ) break;
				result = 0;
			} while (false);
		} catch (Exception e) {
			Close();
			e.printStackTrace();
		}
		if (result == 0)
			return recv_data;
		else
			return null;
	}

	@Override
	public String ConnIpAddr() {
		if (null != tcp_client) {
			return tcp_client.getInetAddress().getHostName();
		}
		return "";
	}

	@Override
	public int ConnPort() {
		if (null != tcp_client) {
			return tcp_client.getPort();
		}
		return 0;
	}

	@Override
	public int Close() {
		int result = 1;
		if (null != tcp_client) {
			try {
				tcp_client.close();
				tcp_client = null;
				result = 0;
			} catch (Exception e) {
				tcp_client = null;
				e.printStackTrace();
			}
		}
		return result;
	}

	public TCPClientConn(String ip) {
		dev_ip = ip;
		tcp_client = null;
	}
}
